 /**
 * Cake数据模型模块
 *   */

 //导入SQLite3模块
 const sqlite3 = require("sqlite3").verbose();
 //导入工具模块
 const util = require("../../common/util")
//导入配置模块
 const config = require("../../common/config");
 const { resolve } = require("path");
 const { off } = require("process");

 /**
  *   * 构造CakeDB
  */
function CakeDB(){
     this.dbFile = config.dbFile;
     this.instance = null;//CakeDB数据库实例
     this.db = null; //SQLite3实例
}

 /**
 * 创建Cake对象
 */
 CakeDB.getInstance = function(){
    if(!this.instance){
        this.instance = new CakeDB();
   }
      return this.instance;
 };

 /**
  * 连接数据库
  * @returns {Promise}
  */
 CakeDB.prototype.connect = function () {
        return new Promise((resolve, reject) => {
        this.db = new sqlite3.Database(this.dbFile, (err) => {
          if (err) {
            reject(err);
          } else {
            resolve("connect ok.");
          }
        });
      });
    };
    
    /**
     * 关闭数据库
     * @returns  {Promise}
     */
    CakeDB.prototype.close = function () {
      return new Promise((resolve, reject) => {
        this.db.close((err) => {
          if (err) {
            reject(err);
          } else {
            resolve("close ok.");
          }
        });
      });
    };
    
    /**
     * 获取指定ID的蛋糕信息
     * @param {Number} cakeId 蛋糕ID
     * @returns  {Promise}
     */
    CakeDB.prototype.find = function (cakeId) {
      return new Promise((resolve, reject) => {
        let sql = "SELECT * FROM cakes WHERE id = ?";
        let params = [cakeId];
        this.db.get(sql, params, (err, result) => {
          if (err) {
            reject(err);
          } else {
            resolve(result);
          }
        });
      });
    };
    
    /**
     * 获取蛋糕信息列表
     * @param {Number} limit 数量
     * @param {Number} offset 开始
     * @returns  {Promise}
     */
    CakeDB.prototype.findAll = function (limit = -1, offset = -1) {
      return new Promise((resolve, reject) => {
        let sql = "";
        let params = [];
        if (limit === -1) {
          sql = "SELECT * FROM cakes ORDER BY id";
        } else if (offset === -1) {
          sql = "SELECT * FROM cakes ORDER BY id LIMIT ?";
          params[0] = limit;
        } else {
          sql = "SELECT * FROM cakes ORDER BY id LIMIT ? OFFSET ?";
          params[0] = limit;
          params[1] = offset;
        }
        this.db.all(sql, params, (err, result) => {
          if (err) {
            reject(err);
          } else {
            resolve(result);
          }
        });
      });
    };
    
    /**
     * 新增蛋糕
     * @param {Object} cake 蛋糕数据
     * @returns  {Promise}
     */
    CakeDB.prototype.add = function (cake) {
      return new Promise((resolve, reject) => {
        let sql = `INSERT INTO cakes (
                name, pic, local_pic, rule, price, 
                 isbn, intro, doubanId, created_time, 
                updated_time
            ) VALUES (
                ?, ?, ?, ?, ?, ?, ?, ?, ?,
                ?
            );`;
        let params = [
          cake.name,
          cake.pic,
          cake.local_pic,
          cake.rule,
          cake.price,
          cake.isbn,
          cake.intro,
          cake.doubanId,
          cake.created_time,
          cake.updated_time,
        ];
    
        this.db.run(sql, params, (err, result) => {
          if (err) {
            reject(err);
          } else {
            resolve(this.lastID); //插入的数据的自增ID
          }
        });
      });
    };
    
    /**
     * 修改蛋糕
     * @param {Object} cake 蛋糕数据
     * @returns  {Promise}
     */
    CakeDB.prototype.update = function (cake) {
      return new Promise((resolve, reject) => {
        let sql = `UPDATE cakes SET
                name = ?, pic = ?, local_pic = ?, rule = ?, 
                price = ?, 
                isbn = ?, intro = ?, 
                doubanId = ?, updated_time = ?
                WHERE id = ?
            ;`;
        let params = [
          cake.name,
          cake.pic,
          cake.local_pic,
          cake.rule,
          cake.price,
          cake.isbn,
          cake.intro,
          cake.doubanId,
          cake.updated_time,
          cake.id,
        ];
    
        this.db.run(sql, params, (err, result) => {
          if (err) {
            reject(err);
          } else {
            resolve(this.changes); //影响的记录数
          }
        });
      });
    };
    
    /**
     * 删除蛋糕
     * @param {Number} cakeId 蛋糕ID
     * @returns  {Promise}
     */
    CakeDB.prototype.remove = function (cakeId) {
      return new Promise((resolve, reject) => {
        let sql = "DELETE FROM cakes WHERE id = ?";
        let params = [cakeId];
        this.db.run(sql, params, (err, result) => {
          if (err) {
            reject(err);
          } else {
            resolve(this.changes); //影响的记录数
          }
        });
      });
    };
    
    module.exports = CakeDB;

